// 这个文件专门存放关于“我的”模块的所有接口

const customer = require('koa-router')()
const db = require('../util/db')
const wxkey = require('./wxkey.js')
const { httpcli } = require('gohttp')
const token = require('titbit-token')

// get请求
// https://api.lzjlw.top:3030/customer/collections?userId=001
customer.get('/collections', async (ctx) => {
    let userId = ctx.query.userId
    console.log(userId)
    let selectSql = `select collections.videoId,video_Img,videoUrl,video_Title,play_Time,type,stage from interactive_video,collections where userId='${userId}' and collections.videoId=interactive_video.videoId`
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve(result)
            }
        })
    })
    ctx.body = res
})

// https://api.lzjlw.top:3030/customer/thumbs_Up?userId=001 && type=1
customer.get('/thumbs_Up', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    let selectSql = `select videoId,video_Img,videoUrl,video_Title,play_Time,thumbs_up.type,stage from interactive_video,thumbs_up 
    where userId='${newObj.userId}' and thumbs_up.type=${newObj.type} and thumbs_up.from_id=interactive_video.videoId`
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve(result)
            }
        })
    })
    ctx.body = res
})

// https://api.lzjlw.top:3030/customer/play_History?userId=001
customer.get('/play_History', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    let selectSql = `select play_history.videoId,video_Img,videoUrl,video_Title,play_history.play_Time,type,stage from interactive_video,play_history 
    where userId='${newObj.userId}' and play_history.videoId=interactive_video.videoId`
    let res = await new Promise((resolve, reject) => {
        db.query(selectSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve(result)
            }
        })
    })
    ctx.body = res
})



// post请求
// https://api.lzjlw.top:3030/customer/user
customer.post('/user', async (ctx) => {
    let result = tok.verify(ctx.request.header.authorization)
    let obj = ctx.request.body
    let user = {
        userId: result.data.openid,
        userName: obj.userName,
        sex: obj.sex,
        age: obj.age,
        head_Photo: obj.head_Photo
    }
    if (result.ok) {
        let selectSql = `select * from user`
        let users = await new Promise((resolve, reject) => {
            db.query(selectSql, (err, result) => {
                if (err) {
                    throw err
                }
                else {
                    resolve(result)
                }
            })
        })
        let flag = false
        // 判断数据库user表中是否含有请求中的openid
        for (key in users) {
            if (users[key].userId == result.data.openid) {
                flag = true
            }
        }
        // 如果没有，则进行插入
        if (flag == false) {
            let insertSql = `insert into user(userId,userName,sex,age,head_Photo) values('${result.data.openid}','${obj.userName}','${obj.sex}',${obj.age},'${obj.head_Photo}')`
            console.log(insertSql)

            let res = await new Promise((resolve, reject) => {
                db.query(insertSql, (err, result) => {
                    if (err) {
                        throw err
                    }
                    else {
                        resolve(user)
                    }
                })
            })
            ctx.body = user
        } else {//如果有，则进行更新
            let updateSql = `update user set userName='${obj.userName}',sex='${obj.sex}',age=${obj.age},
            head_Photo='${obj.head_Photo}' where userId='${result.data.openid}'`
            await new Promise((resolve, reject) => {
                db.query(updateSql, (err, data) => {
                    if (err) {
                        throw err
                    } else {
                        resolve(data)
                    }
                })
            })
            ctx.body = user
        }

    } else {
        ctx.status = 500
        ctx.body = JSON.stringify('出错啦~登录失败')
    }
})


// 修改信息
// https://api.lzjlw.top:3030/customer/user/1
customer.put('/user/:userId', async (ctx) => {
    let userId = ctx.params.userId
    let obj = ctx.request.body
    //防止mysql注入
    var name = obj.userName
    var age = obj.age
    var sex = obj.sex
    var sql = "update ?? set ?? = ?, ?? = ?, ?? = ? where ?? = ?"
    var inserts = ['user', 'userName', name, 'age', age, 'sex', sex, 'userId', userId]
    var updateSql = mysql.format(sql, inserts)
    console.log(updateSql)
    console.log("hahha ")
    // let updateSql = `update user set userName='${obj.userName}',age=${obj.age},sex='${obj.sex}' 
    // where userId='${userId}' `
    let res = await new Promise((resolve, reject) => {
        db.query(updateSql, (err, result) => {
            if (err) {
                throw err
            }
            else {
                resolve('update success')
            }
        })
    })
    ctx.body = res
})



// delete请求
// https://api.lzjlw.top:3030/customer/collections?userId=1 && videoId=1
customer.delete('/collections', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    let deleteSql = `delete from collections where userId='${newObj.userId}' and videoId=${newObj.videoId}`
    let res = await new Promise((resolve, reject) => {
        db.query(deleteSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve('delete success')
            }
        })
    })
    ctx.body = res
})


// https://api.lzjlw.top:3030/customer/thumbs_Up?userId=1 && videoId=1 && type=1
customer.delete('/thumbs_Up', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    let deleteSql = `delete from thumbs_up 
    where userId='${newObj.userId}' and from_Id=${newObj.videoId} and type=${newObj.type}`
    let res = await new Promise((resolve, reject) => {
        db.query(deleteSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve('delete success')
            }
        })
    })
    ctx.body = res
})

// https://api.lzjlw.top:3030/customer/play_History?userId=1 && videoId=1
customer.delete('/play_History', async (ctx) => {
    let obj = ctx.query
    // 利用正则表达式去除空格
    str = JSON.stringify(obj).toString().replace(/\s*/g, "")
    newObj = JSON.parse(str)
    let deleteSql = `delete from play_history
    where userId='${newObj.userId}' and videoId=${newObj.videoId}`
    let res = await new Promise((resolve, reject) => {
        db.query(deleteSql, (err, result) => {
            if (err) {
                throw err
            } else {
                resolve('delete success')
            }
        })
    })
    ctx.body = res
})


// 批量删除
// https://api.lzjlw.top:3030/customer/batch/play_History?userId=1&&videoId=1
customer.delete('/batch/:tableType', async (ctx) => {
    let tableType = ctx.params.tableType
    let obj = ctx.query
    let itemId = ctx.request.body.itemId
    console.log(itemId)
    // let itemArr = itemId.filter(function (item, index, self) {
    //     return self.indexOf(item) == index;
    // })

    if (tableType == 'collections') {
        let num = 0
        for (key in itemId) {
            let deleteSql = `delete from ${tableType} where userId='${obj.userId}' and videoId=${itemId[key]}`
            await new Promise((resolve, reject) => {
                db.query(deleteSql, (err, data) => {
                    if (err) {
                        throw err
                    }
                    else {
                        num++;
                        resolve(data)
                    }
                })
            })
        }
        if (num == itemId.length) {
            ctx.body = 'delete success'
        } else {
            ctx.body = '啊哦，出了点小问题~'
        }
    } else if (tableType == 'play_history') {
        let num = 0
        for (key in itemId) {
            console.log(itemId[key])
            let deleteSql = `delete from ${tableType} where userId='${obj.userId}' and videoId=${itemId[key]}`
            await new Promise((resolve, reject) => {
                db.query(deleteSql, (err, data) => {
                    if (err) {
                        throw err
                    }
                    else {
                        num++;
                        resolve(data)
                    }
                })
            })
        }
        console.log(num)
        console.log(itemId.length)
        if (num == itemId.length) {
            ctx.body = 'delete success'
        } else {
            ctx.body = '啊哦，系统出了点小问题~'
        }
    } else if (tableType == 'thumbs_up') {
        let num = 0
        for (key in itemId) {
            console.log(itemId[key])
            let deleteSql = `delete from ${tableType} where userId='${obj.userId}' and 
            from_Id=${itemId[key]} and type=${obj.type}`
            console.log(deleteSql)
            await new Promise((resolve, reject) => {
                db.query(deleteSql, (err, data) => {
                    if (err) {
                        throw err
                    }
                    else {
                        num++;
                        resolve(num)
                    }
                })
            })

        }
        console.log(num)
        console.log(itemId.length)
        if (num == itemId.length) {
            ctx.body = 'delete success'
        } else {
            ctx.body = '啊哦，系统出了点小问题~'
        }
    }
})




// 会话登录验证
let tok = new token({
    // token解密验证3600秒即为超时（token有效期，单位为秒）
    expires: 31536000,
    // 必须是32位字符
    key: 'ashdisjow82910wjsidhaolp9748wj1s',//加密字符

    // 必须是16位字符
    iv: '18dhsjaosjwosnvj'//干扰项
})
// 返回token值
customer.get('/login/:code', async (ctx) => {
    let code = ctx.params.code
    console.log(code)
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
        + `?appid=${wxkey.appid}&secret=${wxkey.secret}`
        + `&js_code=${code}&grant_type=authorization_code`

    let ret = await httpcli.get(auth_url)
        .then(res => {
            return res.json()
        })

    if (!ret.openid) {
        ctx.status = 500
        ctx.body = JSON.stringify(ret)
        return
    }

    ctx.body = tok.make(ret)
})


customer.get('/user', async (ctx) => {
    // console.log(ctx.request.header.authorization)
    let result = tok.verify(ctx.request.header.authorization)
    if (result.ok) {
        let selectSql = `select * from user where userId='${result.data.openid}'`
        let res = await new Promise((resolve, reject) => {
            db.query(selectSql, (err, data) => {
                if (err) {
                    throw err
                } else {
                    resolve(data)
                }
            })
        })
        ctx.body = res
    }
    else{
        ctx.status=500
        ctx.body=result
    }

    
})

module.exports = customer